<template>
  <div>
    <table class="el-table__body" cellspacing="0" cellpadding="0" border="0">
      <tbody>
        <tr v-if="flBodyfile!=null">
          <td class="tdlbl tdw17"><sapn v-if="fileIsMust===1" class="required">*</sapn>{{ bodyFileTitle }}</td>
          <td class="tdcont tdw83" colspan="3">
            <el-upload
              v-if="!flBodyfile.id"
              ref="upload"
              :on-change="handleUploadChange"
              action=""
              multiple="false"
              :file-list="fileList"
              :show-file-list="false"
              :auto-upload="false"
              :with-credentials="true"
              :accept="accept"
            >
              <el-input v-model="flBodyfile.file.name" name="bodyfileName" :placeholder="'请选择'+bodyFileTitle">
                <el-button slot="append" size="mini" icon="el-icon-upload2" />
              </el-input>
            </el-upload>
            <div v-if="flBodyfile && flBodyfile.id" style="width:100%;">
              <el-link type="primary" :underline="false" @click="viewBodyfile(flBodyfile)">{{ flBodyfile.fileName }}</el-link>
              <el-link
                v-if="flDocfile&&downloadDoc"
                class="docfileIcon"
                type="primary"
                title="下载文件"
                icon="el-icon-download"
                :underline="false"
                @click="downloadDocfile(flDocfile)"
              />
              <el-link
                v-if="(curTN.tnCanEdit===1 && curTN.userName===flBodyfile.uploadBy && flBodyfile.notDelete!==true) || (deleteFileNodes && curTN.tnNodeName && deleteFileNodes.indexOf(curTN.tnNodeName) > -1)"
                class="removeBodyfileIcon"
                type="danger"
                title="删除文件"
                icon="el-icon-close"
                :underline="false"
                @click="removeBodyfile(flBodyfile)"
              />
              <div v-if="extName==='.pdf' && fileNeedSign==1" style="float:right;"><el-button size="mini" style="border: 0px;" @click="viewBodyfile(flBodyfile,'sign')">签名</el-button></div>
              <div v-if="flBodyfile.fileId" style="float:right;"><el-button size="mini" style="border: 0px;" @click="viewHistoryfile(flBodyfile)">历史版本</el-button></div>
            </div>

          </td>
        </tr>
      </tbody>
    </table>

    <div v-if="historyDialogVisible" class="file-right-box">
      <div class="right-box-div1">
        <el-row class="navbar">
          <el-col :span="20">历史版本</el-col><el-col :span="4"><i class="el-icon-close" @click="historyDialogVisible=false" /></el-col>
        </el-row>
        <el-scrollbar :native="false">
          <div v-for="(attach,index) in historyFiles.filter((obj)=>(obj.fileName.indexOf('.doc') === -1||obj.filePath.indexOf('/noTracks/')!==-1))" :key="index" class="fileitem">
            <div style="cursor:pointer;" @click="viewBodyfile(attach)">
              <el-row style="line-height: 28px">
                <el-col :span="4"> <el-avatar size="small" :src="attach.avatarUrl" /></el-col>
                <el-col :span="6">{{ attach.updateBy }}</el-col>
                <el-col :span="14" style="text-align:right">{{ attach.updateTime }} </el-col>
              </el-row>
            </div>
            <el-row>
              <el-col :span="14" style="padding-left:5px;"><div style="cursor:pointer;" @click="viewBodyfile(attach)">{{ attach.fileVer }}</div></el-col>
              <el-col :span="6">{{ attach.fileStatus==1?'当前版本':'历史版本' }}</el-col>
              <el-col style="text-align:right" :span="4">
                <el-dropdown @command="moreMenuitemClick">
                  <span class="el-dropdown-link">
                    <i class="el-icon-more" />
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item icon="el-icon-view" :command="'view_'+attach.id">查看</el-dropdown-item>
                    <el-dropdown-item v-if="(curTN.tnCanEdit===1 && curTN.userName===flBodyfile.uploadBy) || (deleteFileNodes && curTN.tnNodeName && deleteFileNodes.indexOf(curTN.tnNodeName) > -1)" icon="el-icon-close" :command="'remove_'+attach.id">删除</el-dropdown-item>
                    <el-dropdown-item icon="el-icon-download" :command="'download_'+attach.id">下载</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </el-col>
            </el-row>
          </div>

        </el-scrollbar>
      </div>
    </div>

  </div>
</template>

<script>
import { formatFileSize, formatTime } from '@/global/utils/index'
import { mapGetters } from 'vuex'

export default {
    name: 'BodyFile',
    components: {

    },
    props: {
        vo: { type: Object, default: function() { return {} } },
        curTN: { type: Object, default: function() { return {} } },
        flBodyfile: { type: Object, default: function() { return { file: { name: '' }} } },
        attachments: { type: Array, default: function() { return [] } },
        wfAttachUrl: { type: String, default: 'wfInstance/wfBusiAttach' },
        fileNeedSign: { type: Number, default: 0 },
        accept: { type: String, default: '.doc,.pdf' },
        viewer: { type: String, default: 'pdfjs' },
        viewerUrlParams: { type: String, default: '' }, // 在线预览扩展参数
        bodyFileTitle: { type: String, default: '文件正文' },
        fileIsMust: { type: Number, default: 0 },
        autoSave: { type: Boolean, default: false },
        waterMark: { type: Boolean, default: false },
        downloadDoc: { type: Boolean, default: false },
        markContent: { type: String, default: '' },
        deleteFileNodes: { type: String, default: '' }
    },
    data() {
        return {
            extName: '',
            flDocfile: null,
            historyFiles: [],
            historyDialogVisible: false,
            loading: true
        }
    },
    computed: {
        ...mapGetters([
            'loginUser'
        ])
    },
    watch: {
        flBodyfile() {
            if (this.flBodyfile !== null) {
                this.setExtName()
            } else {
                this.flBodyfile = { file: { name: '' }}
            }
        }
    },
    created() {

    },
    beforeDestroy() {

    },
    mounted() {
        if (this.flBodyfile !== null) {
            this.setExtName()
        } else {
            this.flBodyfile = { file: { name: '' }}
        }
    },
    methods: {
        setExtName() {
            if (this.flBodyfile === undefined || this.flBodyfile === null) this.flBodyfile = { file: { name: '' }}
            if (this.flBodyfile && this.flBodyfile.originalName) this.extName = this.flBodyfile.originalName.substring(this.flBodyfile.originalName.indexOf('.')).toLowerCase()
            this.extName = this.extName.replace('.des', '').replace('.xor', '').replace('.rsm3', '')

            this.attachments.forEach(attach => {
                if (attach.fileType === 'BODY' && attach.filePath.indexOf('/noTracks/') === -1 && (attach.originalName === this.flBodyfile.originalName.replace(this.extName, '.doc') || attach.originalName === this.flBodyfile.originalName.replace(this.extName, '.docx'))) {
                    this.flDocfile = attach
                }
            })
        },
        viewBodyfile(flBodyfile, sign) {
            if (flBodyfile.id === undefined) return

            if (this.extName === '.pdf' && (this.viewer === 'pdfjs' || sign === 'sign')) {
                let fileurl = process.env.VUE_APP_BASE_API + '/' + this.wfAttachUrl + '/downloadById?inline=true&attachIds=' + flBodyfile.id + '&saveAs=' + this.flBodyfile.fileName
                fileurl += '&httpPort=' + location.port
                if (sign === 'sign') {
                    fileurl += '&filename=' + decodeURIComponent(this.flBodyfile.fileName)
                    window.open('#/viewpdffile?sign&fileurl=' + encodeURIComponent(encodeURIComponent(fileurl)))
                } else {
                    window.open('/plugins/PDFjs/web/viewer.html?file=' + encodeURIComponent(fileurl + (this.waterMark ? ('&waterMark=' + this.waterMark + '&markContent=' + this.markContent) : '')))
                }
            } else if (this.viewer.indexOf('dcs=') === 0) {
                this.$http({
                    method: 'GET',
                    url: 'base/user/getSessionId'
                }).then(res => {
                    if (res.code === 'success') {
                        const tSessionId = res.body.tSessionId
                        const hostname = location.href.split('#')[0]
                        let downUrl = hostname.substring(0, hostname.length - 1) + process.env.VUE_APP_BASE_API + '/' + this.wfAttachUrl + '/downloadById?attachIds=' + flBodyfile.id + '&httpPort=' + location.port + '&tSessionId=' + tSessionId

                        let convertType = '0'
                        if (this.extName === '.ofd') {
                            convertType = '21'
                        } else if (this.extName === '.pdf' || this.extName === '.pdfx') {
                            convertType = '20'
                        }

                        downUrl = this.viewer.split('=')[1] + '/composite/httpfile?convertType=' + convertType + '&fileUrl=' + encodeURIComponent(downUrl)
                        if (this.viewerUrlParams) {
                            downUrl += '&' + this.viewerUrlParams
                        }
                        if (downUrl.indexOf('&acceptTracks=0') === -1) {
                            downUrl += '&acceptTracks=0'
                        }

                        this.$bus.emit('showDoingDialog', '正在下载文件，请稍候...')
                        $.post(downUrl, { }, res => {
                            this.$bus.emit('closeDoingDialog')
                            if (res.errorcode === 0) {
                                window.open(res.data.viewUrl)
                            } else {
                                this.$alert(res.message, '操作提示', { type: 'error' })
                            }
                        }, 'json')
                    }
                })
            } else {
                const downUrl = process.env.VUE_APP_BASE_API + '/' + this.wfAttachUrl + '/downloadById?inline=true&attachIds=' + flBodyfile.id + '&httpPort=' + location.port + (this.waterMark ? ('&waterMark=' + this.waterMark + '&markContent=' + this.markContent) : '')
                window.open(downUrl)
            }
        },
        downloadDocfile(flDocfile) {
            const downUrl = process.env.VUE_APP_BASE_API + '/' + this.wfAttachUrl + '/downloadById?attachIds=' + flDocfile.id + '&httpPort=' + location.port
            window.open(downUrl)
        },
        removeBodyfile(flBodyfile) {
            let confirmMsg = '您是否确认删除当前的文件？'
            if (flBodyfile.fileStatus === 8) {
                confirmMsg = '您是否确认删除历史版本文件？'
            }
            var _this = this
            this.$confirm(confirmMsg, '确认操作', { type: 'warning' })
                .then(async() => {
                    if (flBodyfile.fileStatus !== 8) {
                        document.querySelector('.removeBodyfileIcon').innerHTML = '&nbsp;正在删除...'
                    }
                    var deleteIds = flBodyfile.id
                    var originalName = flBodyfile.originalName.substring(0, flBodyfile.originalName.lastIndexOf('.'))

                    for (var i = 0; i < _this.attachments.length; i++) {
                        if (_this.attachments[i].id && _this.attachments[i].id !== flBodyfile.id && _this.attachments[i].originalName && _this.attachments[i].originalName.substring(0, _this.attachments[i].originalName.lastIndexOf('.')) === originalName) {
                            if (!flBodyfile.fileVer || (flBodyfile.fileVer && flBodyfile.fileVer === _this.attachments[i].fileVer)) {
                                deleteIds += ',' + _this.attachments[i].id
                            }
                        }
                    }

                    this.$http({
                        method: 'DELETE',
                        contentType: 'application/x-www-form-urlencoded',
                        params: { attachIds: deleteIds },
                        url: this.wfAttachUrl + '/delete'
                    }).then(res => {
                        if (res.code === 'success') {
                            for (var i = 0; i < this.attachments.length; i++) {
                                if (this.attachments[i].id === flBodyfile.id || this.attachments[i].originalName === originalName + '.pdf') {
                                    this.attachments.splice(i--, 1)
                                }
                            }
                            if (flBodyfile.fileStatus !== 8) {
                                this.flBodyfile = { file: { name: '' }}
                                this.$vnode.context.bodyfile = this.flBodyfile

                                if (typeof this.vo.flBodyFilename !== 'undefined') this.vo.flBodyFilename = null
                                if (typeof this.vo.signedFileName !== 'undefined') this.vo.signedFileName = null

                                this.$vnode.context.commandBar.forEach(btn => {
                                    if (btn.btnCode === 'btnOpenWordClick') {
                                        btn.btnShow = true
                                    }
                                })
                                if (!res.body.restoreHistoryFile) {
                                    this.$vnode.context.wfInstance.haveDoc = 0
                                }
                                this.$vnode.context.btnSaveClick()
                            } else {
                                this.viewHistoryfile(this.flBodyfile)
                            }
                        } else {
                            this.$alert(res.message, '操作提示', { type: 'error' })
                        }
                    })
                })
        },
        handleUploadChange(file, fileList) {
            const extName = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
            if (this.accept.indexOf(extName) === -1) {
                this.$alert('您上传的文件格式有误，仅支持' + this.accept.replace(/,/g, '、') + '格式的文件！', '提示', { confirmButtonText: '确定', type: 'warning' })
                this.fileList = []
                return
            }
            if (this.flBodyfile != null && this.flBodyfile.name !== '') {
                for (var i = 0; i < this.attachments.length; i++) {
                    if (this.attachments[i].name === this.flBodyfile.name && this.attachments[i].fileType === 'BODY' && this.attachments[i].uploadTime === '待上传') {
                        this.attachments.splice(i--, 1)
                    }
                }
            }
            const attach = {}
            attach.fileName = file.name
            attach.fileSize = formatFileSize(file.size)
            attach.fileType = 'BODY'
            attach.uploadBy = this.loginUser.personName
            attach.uploadTime = '待上传'
            attach.file = file
            attach.checked = false
            file.progress = 0

            this.flBodyfile = attach
            this.$vnode.context.bodyfile = attach

            if (this.autoSave) {
                this.$bus.emit('showDoingDialog', '正在上传正文...')
                this.$vnode.context.btnSubmitClick('AutoSave')
            }
        },
        viewHistoryfile(file) {
            this.loading = true
            this.historyDialogVisible = true

            const listdataUrl = this.wfAttachUrl + '/listAttach'

            this.$http({
                method: 'POST',
                contentType: 'application/x-www-form-urlencoded',
                params: { pageNum: 1, pageSize: 1000, orderBy: 'fileVer desc', urlsearch: 'fileId:' + file.fileId },
                url: listdataUrl
            }).then(res => {
                if (res.code === 'success') {
                    this.historyFiles = res.body.pageInfo.list.filter(attach => {
                        attach.updateTime = formatTime(attach.updateTime)
                        attach.avatarUrl = process.env.VUE_APP_BASE_API + '/base/user/downloadPhotoByAccount?orgCode=' + attach.orgCode + '&account=' + attach.updateBy + '&httpPort=' + location.port
                        return true
                    })
                } else {
                    this.$alert(res.message, '操作提示', { type: 'error' })
                }
                this.loading = false
            })
        },
        moreMenuitemClick(command) {
            const files = this.historyFiles.filter(file => {
                if (command.indexOf(file.id) > 0) {
                    return true
                }
            })

            if (command.indexOf('view') !== -1) {
                this.viewBodyfile(files[0])
            } else if (command.indexOf('remove') !== -1) {
                this.removeBodyfile(files[0])
            } else if (command.indexOf('download') !== -1) {
                let attachIds = files[0].id
                this.historyFiles.forEach(attach => {
                    if (attach.fileVer && attach.fileVer === files[0].fileVer && attach.id !== files[0].id) {
                        attachIds += ',' + attach.id
                    }
                })
                const downUrl = process.env.VUE_APP_BASE_API + '/' + this.wfAttachUrl + '/downloadById?attachIds=' + attachIds + '&httpPort=' + location.port + '&saveAs=文件正文_' + files[0].fileVer + '.zip'
                window.open(downUrl)
            }
        }
    }
}
</script>

<style scoped lang="scss">
    /deep/ .el-upload--text{
        width:100%;
    }
    /deep/ .el-upload .el-input-group .el-input__inner{
       display:inline-block;
       vertical-align:baseline;
    }

    .docfileIcon{
        padding-left: 10px;
        padding-right: 10px;
    }

.file-right-box{
    position: fixed;
    bottom: 0;
    top: 63px;
    right: 5px;
    height: 100%;
    z-index:1199;

    .right-box-div1{
        float: left;
        height: 100%;
        width: 260px;
        background: #fff;
        border-left: 1px solid #ddd;
        overflow: hidden;
        font-size: 14px;
        /deep/ .el-scrollbar {
            height:calc(100vh - 110px);
            width: 100%;
            .el-scrollbar__wrap {
                // overflow-y: auto;
                overflow-x: auto;
            }
        }

        .navbar{
            padding: 12px;
            font-size: 14px;
            font-weight: 600;

            /deep/ .el-icon-close{
                float: right;
                cursor: pointer;
            }
        }
        .fileitem{
            padding:10px;
            font-size: 13px;
            border-bottom: solid 1px #f3f3f3;
            border-top: solid 1px #f3f3f3;

            .el-dropdown-link{
                cursor: pointer;
            }
        }
    }
}
</style>
